package com.alibaba.nacos.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.io.InputStream;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JacksonUtils {

    static ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }


    @SneakyThrows
    public static String toJson(Object object) {
        return mapper.writeValueAsString(object);
    }

    @SneakyThrows
    public static <T> T toObj(String json,
                              Class<T> clazz) {
        return mapper.readValue(json, clazz);
    }

    @SneakyThrows
    public static byte[] toJsonBytes(Object obj) {
        return mapper.writeValueAsBytes(obj);
    }

    @SneakyThrows
    public static <T> T toObj(InputStream inputStream,
                              Class<T> cls) {
        return mapper.readValue(inputStream, cls);
    }

    @SneakyThrows
    public static <T> T toObj(byte[] bytes,
                              Class<T> tClass) {
        return mapper.readValue(bytes, tClass);
    }
}
